package com.hulk.dryad.common.respone.component;

import com.hulk.dryad.common.annotation.RespData;
import com.hulk.dryad.common.annotation.RespExcel;
import com.hulk.dryad.common.annotation.RespSha256;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.exception.BaseRteException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import javax.validation.ConstraintViolationException;
import java.lang.reflect.Method;
import java.util.stream.Collectors;


/**
 * @author hulk
 * @date 2019/10/17
 * 重写返回体,全局业务异常拦截。
 */
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE-1)
@RestControllerAdvice(basePackages = "com.hulk.dryad")
public class ResponseDataBodyAdvice implements ResponseBodyAdvice<Object> {



	/** 类上或者方法上是否有RespResult注解，有进行如下处理，没有直接返回。*/
	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		Method method = returnType.getMethod();
		boolean isMethodRespExcelAnnotated = AnnotatedElementUtils.isAnnotated(method, RespExcel.class);
		if(isMethodRespExcelAnnotated){
			return false;
		}
		boolean isMethodRespSha256Annotated = AnnotatedElementUtils.isAnnotated(method, RespSha256.class);
		if(isMethodRespSha256Annotated){
			return false;
		}
		boolean isMethodRespDataAnnotated = AnnotatedElementUtils.isAnnotated(method, RespData.class);
		if(isMethodRespDataAnnotated&& (!isMethodRespSha256Annotated )){
			return true;
		}
		Class<?> targetClass = method.getDeclaringClass();
	    boolean isClazzRespSha256Annotated	= AnnotatedElementUtils.isAnnotated(targetClass, RespSha256.class);
		if(isClazzRespSha256Annotated){
			return false;
		}
		boolean isClazzRespDataAnnotated	= AnnotatedElementUtils.isAnnotated(targetClass, RespData.class);
		if(isClazzRespDataAnnotated&& (!isClazzRespSha256Annotated )){
			return true;
		}
		return false;
	}

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

		if (body == null) {
			return null;
		}
        if (body instanceof R<?>) {
            return body;
        }
        if (body instanceof BEC) {
            BEC rc = (BEC) body;
            return R.failed(rc.getErrCode(), rc.getErrDesc());
        }
        return R.ok(body);
    }

    @ExceptionHandler(BaseRteException.class)
    public R handleBaseRteException(BaseRteException e) {
        log.error("BaseRteException:", e);
        return R.failed(e.getErrCode(), e.getErrDesc());
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("DuplicateKeyException:", e);
        return  R.failed(BEC.E_2019.getErrCode(),BEC.E_2019.getErrDesc()) ;
    }
	@ExceptionHandler(BindException.class)
	public R  handleBindException(BindException e) {
		log.error("BindException:", e);
    	String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
		return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message) ;
	}
	@ExceptionHandler(ConstraintViolationException.class)
	public R handleConstraintViolationException(final ConstraintViolationException e) {
		log.error("ConstraintViolationException:", e);
    	String message = e.getConstraintViolations().stream().map(javax.validation.ConstraintViolation::getMessage).collect(Collectors.joining());
		return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message) ;
	}
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:", e);
		String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
		return   R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message) ;
    }
    @ExceptionHandler(IllegalArgumentException.class)
    public R handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("illegalArgumentExceptionException:", e);
        return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()) ;
    }
    @ExceptionHandler(Exception.class)
    public R handleGlobalException(Exception e) {
        log.error("Exception", e);
        return   R.failed(BEC.E_9999.getErrCode(),BEC.E_9999.getErrDesc()) ;
    }
}
